﻿using CommunityToolkit.Mvvm.Input;
using MaterialDesignThemes.Wpf;
using StudentInfoSystem.Core.Models;
using StudentInfoSystem.Core.Utils;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Win32; // 添加文件对话框支持
using System.IO;

namespace StudentInfoSystem.UI.ViewModels;

public class SettingsViewModel : INotifyPropertyChanged
{
    private readonly AppSettings _settings;
    public SettingsViewModel(AppSettings settings)
    {
        _settings = settings;

        // 初始化命令
        ResetSettingsCommand = new RelayCommand(ResetSettings);
        ExportDataCommand = new RelayCommand(ExportData);
        ImportDataCommand = new RelayCommand(ImportData);
        ExportSettingsCommand = new RelayCommand(ExportSettings);
        ImportSettingsCommand = new RelayCommand(ImportSettings);

        // 初始化命令
        BrowseBackgroundImageCommand = new RelayCommand(BrowseBackgroundImage);
        UseDefaultBackgroundCommand = new RelayCommand(UseDefaultBackground);
    }

    // 命令
    public ICommand ResetSettingsCommand { get; }
    public ICommand ExportDataCommand { get; }
    public ICommand ImportDataCommand { get; }
    public ICommand ExportSettingsCommand { get; } // 新增：导出设置命令
    public ICommand ImportSettingsCommand { get; } // 新增：导入设置命令
    public ICommand BrowseBackgroundImageCommand { get; }
    public ICommand ResetBackgroundImageCommand { get; }
    public ICommand UseDefaultBackgroundCommand { get; }
    private void UseDefaultBackground()
    {
        // 将背景路径设置为空字符串表示使用默认背景
        BackgroundImagePath = string.Empty;
    }
    private void BrowseBackgroundImage()
    {
        var openFileDialog = new OpenFileDialog
        {
            Filter = "图像文件|*.jpg;*.jpeg;*.png;*.bmp|所有文件|*.*",
            Title = "选择背景图片"
        };

        if (openFileDialog.ShowDialog() == true)
        {
            BackgroundImagePath = openFileDialog.FileName;
        }
    }


    // 添加 IsSideMenuButtonEffectEnabled 属性
    public bool IsSideMenuButtonEffectEnabled
    {
        get => _settings.ButtonEffectVisibility == Visibility.Visible;
        set
        {
            _settings.ButtonEffectVisibility = value ? Visibility.Visible : Visibility.Collapsed;
            OnPropertyChanged();
        }
    }

    private void ResetSettings()
    {
        // 询问用户确认
        var result = MessageBox.Show("确定要重置所有设置为默认值吗？",
            "确认重置", MessageBoxButton.YesNo, MessageBoxImage.Question);

        if (result != MessageBoxResult.Yes) return;

        try
        {
            // 创建新的默认设置实例
            var defaultSettings = new AppSettings();

            // 保留当前用户信息（不重置）
            var currentUser = _settings.CurrentUser;

            // 复制默认设置到当前设置
            CopySettings(defaultSettings, _settings);

            // 恢复当前用户
            _settings.CurrentUser = currentUser;

            // 立即保存重置后的设置
            JsonData.Save(_settings);

            // 刷新所有UI绑定
            RefreshAllBindings();

            MessageBox.Show("设置已重置为默认值", "重置成功",
                MessageBoxButton.OK, MessageBoxImage.Information);
        }
        catch (Exception ex)
        {
            MessageBox.Show($"重置设置时出错: {ex.Message}", "重置错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ExportData()
    {
        // TODO: 实现数据导出逻辑
        MessageBox.Show("数据导出功能即将在下一版本实现", "功能开发中",
            MessageBoxButton.OK, MessageBoxImage.Information);
    }

    private void ImportData()
    {
        // TODO: 实现数据导入逻辑
        MessageBox.Show("数据导入功能即将在下一版本实现", "功能开发中",
            MessageBoxButton.OK, MessageBoxImage.Information);
    }

    private void ExportSettings()
    {
        try
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = "JSON 文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                FileName = "StudentInfoSystem_Settings.json",
                DefaultExt = ".json"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                // 使用JsonData保存到用户选择的位置
                JsonData.Save(_settings, saveFileDialog.FileName);
                MessageBox.Show("设置导出成功！", "导出成功",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"导出设置时出错: {ex.Message}", "导出错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    private void ImportSettings()
    {
        try
        {
            var openFileDialog = new OpenFileDialog
            {
                Filter = "JSON 文件 (*.json)|*.json|所有文件 (*.*)|*.*",
                DefaultExt = ".json"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                var result = MessageBox.Show("导入设置将覆盖当前所有设置，是否继续？",
                    "确认导入", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    var importedSettings = JsonData.Load<AppSettings>(openFileDialog.FileName);
                    CopySettings(importedSettings, _settings);

                    // 手动刷新所有UI绑定
                    RefreshAllBindings();

                    MessageBox.Show("设置导入成功！", "导入成功",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show($"导入设置时出错: {ex.Message}", "导入错误",
                MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

    // 添加这个方法刷新所有绑定属性
    private void RefreshAllBindings()
    {
        // 刷新所有属性绑定
        OnPropertyChanged(nameof(IsBackgroundImageEnabled));
        OnPropertyChanged(nameof(IsSideMenuButtonEffectEnabled));
        OnPropertyChanged(nameof(AutoSaveEnabled));
        OnPropertyChanged(nameof(SaveInterval));

        // 同时刷新AppSettings的所有属性
        _settings.RefreshAllProperties();
    }

    // 复制设置属性（排除一些不需要复制的属性）
    private void CopySettings(AppSettings source, AppSettings target)
    {
        // 保存当前用户信息（不覆盖）
        var currentUser = target.CurrentUser;

        // 使用反射复制所有可写属性
        var properties = typeof(AppSettings).GetProperties()
            .Where(p => p.CanWrite && p.CanRead &&
                       p.Name != nameof(AppSettings.CurrentUser) &&
                       p.Name != nameof(AppSettings.UserAccounts));

        foreach (var property in properties)
        {
            var value = property.GetValue(source);
            property.SetValue(target, value);
        }

        // 恢复当前用户
        target.CurrentUser = currentUser;
    }

    // INotifyPropertyChanged 实现
    public event PropertyChangedEventHandler? PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    // ============================ 后台绑定 ===========================
    // 背景图片启闭
    // 添加 BackgroundImagePath 属性
    public string BackgroundImagePath
    {
        get => _settings.BackgroundImagePath;
        set
        {
            _settings.BackgroundImagePath = value;
            OnPropertyChanged();
        }
    }

    // 添加 IsBackgroundImageEnabled 属性
    public bool IsBackgroundImageEnabled
    {
        get => _settings.IsBackgroundImageEnabled;
        set
        {
            _settings.IsBackgroundImageEnabled = value;
            OnPropertyChanged();
        }
    }

    // 自动保存
    public bool AutoSaveEnabled
    {
        get => _settings.AutoSaveEnabled;
        set => _settings.AutoSaveEnabled = value;
    }

    // 保存间隔
    public int SaveInterval
    {
        get => _settings.SaveInterval;
        set
        {
            _settings.SaveInterval = value;
            OnPropertyChanged();
        }
    }
}